const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");
const uuid=require("node-uuid");

http.createServer((req, res)=>{
    if(req.url !== "/favicon.ico"){
        const urlObj = url.parse(req.url,true);
        switch(urlObj.pathname){
            case "/api":
                ajaxHandle(req,res);
                break;
            default:
                fileHandle(req,res);
        }
    }
}).listen("3000");

function ajaxHandle(req,res){
    let data = "";
    req.on("data",(s)=>{
        data += s;
    })
    req.on("end",()=>{
        if(data === ""){
            const urlObj = url.parse(req.url, true);
            data = urlObj.query;
        }else{
            data = querystring.parse(data);
        }
        switch(data.type){
            case "login":
                login(req,res,data);
                break;
            case "register":
                register(req,res,data);
                break;
            case "goods":
                goods(req,res,data);
                break;
            case "user":
                user(req,res,data);
                break;
            default:
                res.write("404");
                res.end();
        }
    })
}

// 假设的数据库
// [{userId:"随机数",user:"admin",pass:123,state:0},{user:"liyang",pass:345,state:0},...]

// node-uuid
// uuid.v1() 同 唯一的意思

let userMsg = [];

function login(req,res,data){
    // console.log(userMsg);
    // 登录
    // 比对用户密码数据
    let i;
    const onoff = userMsg.some((val,idx)=>{
        i = idx;
        return val.user === data.user;
    })

    let msg = {};

    if(onoff){
        if(userMsg[i].pass === data.pass){
            userMsg[i].state = 1;
            msg = {code:200,msg:"登录成功",data:userMsg[i]};
        }else{
            msg = {code:400,msg:"用户名密码不匹配",data:"NOT DATA"}
        }
    }else{
        msg = {code:404,msg:"用户名不存在，需要注册",data:"NOT DATA"}
    }
    res.write(JSON.stringify(msg));
    res.end();
}

function register(req,res,data){
    // 注册
    // 存用户密码数据
    let i;
    // 查看数据库中是否已经有重复数据
    const onoff = userMsg.some((val,idx)=>{
        i=idx;
        return val.user === data.user;
    });

    let msg = {};
    // 如果有重复数据，注册失败
    if(onoff){
        msg = {code:1,msg:"用户名重复",data:"NOT DATA"};
    }else{
        const v1Str = uuid.v1();
        // 没有重复，再进行注册
        userMsg.push({
            userId:v1Str,
            user:data.user,
            pass:data.pass,
            state:0
        })
        msg = {
            code:200,
            msg:"注册成功",
            data:{
                userId:v1Str,
                user:data.user,
                pass:data.pass,
                state:0
            }
        };
    }
    // 前后端交互一定要交互json字符
    res.write(JSON.stringify(msg));
    // 停止当前请求
    res.end();
}

// localhost:3000/api?type=goods
function goods(req,res,data){
    let goodsData = fs.readFileSync("./www/data/goods.json");
    res.write(goodsData);
    res.end();
}

function user(req,res,data){
    res.write("用户数据给你了");
    res.end();
}


function fileHandle(req,res){
    const urlObj = url.parse(req.url);
    const path = "./www" + urlObj.pathname;
    fs.readFile(path,(err,data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}


